<?php

namespace App\Http\Controllers\Home;

use App\Models\Home\UserInfo;
use App\Models\Home\Weibo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;

class FavoriteController extends Controller
{
    //收藏
    public function update($weibo_id)
    {
        //用户id
        $user_id = Session::get('user.id');
        //用户已经收藏的微博id
        $favorites = UserInfo::find($user_id)->favorites;
        //拼接当前微博id
        $favorites .= ',' . $weibo_id;
        //更新favorites字段
        UserInfo::find($user_id)->update(['favorites' => $favorites]);
    }

    //取消收藏
    public function destroy($weibo_id)
    {
        //用户id
        $user_id = Session::get('user.id');
        //用户已经收藏的微博id
        $favorites = UserInfo::find($user_id)->favorites;
        //转数组
        $favorites_array = explode(',', $favorites);
        //该微博id在数组中的位置
        $key = array_search($weibo_id, $favorites_array);
        //从数组中删除该微博id
        array_splice($favorites_array, $key, 1);
        //转字符串
        $favorites = implode(',', $favorites_array);
        //更新favorites字段
        UserInfo::find($user_id)->update(['favorites' => $favorites]);
    }

    //用户收藏的微博列表
    public function index($user_id)
    {
        //取出用户信息
        $info = UserInfo::where('user_id', $user_id)->first();
        //获取我的关注列表
        $follows = UserInfo::where('user_id', Session::get('user.id'))->first()->following;
        $follows = explode(',', $follows);
        //获取收藏列表
        $favorites = UserInfo::where('user_id', $user_id)->first()->favorites;
        $favorites_array = explode(',', $favorites);
        if ($favorites_array[0] === '') {
            array_shift($favorites_array);
        }
        $favorites = Weibo::leftJoin('user_infos', 'user_infos.user_id', '=', 'weibos.user_id')
            ->select('weibos.*', 'user_infos.user_id', 'user_infos.nickname', 'user_infos.avatar')
            ->where('weibos.is_show', 1)
            ->whereIn('weibos.id', $favorites_array)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();
        $a = UserInfo::select('favorites', 'likes')
            ->where('user_id', '=', $user_id)
            ->first()
            ->toArray();
        foreach ($favorites as $k => $v) {
            if ($v['is_forward']) {
                $forward_weibo = Weibo::join('user_infos', 'user_infos.user_id', '=', 'weibos.user_id')
                    ->select('weibos.*', 'user_infos.user_id', 'user_infos.nickname')
                    ->where('weibos.id', $v['is_forward'])
                    ->first()
                    ->toArray();
                $favorites[$k]['is_forward'] = $forward_weibo;
            }
            $favorites[$k]['favorites'] = $a['favorites'];
            $favorites[$k]['likes'] = $a['likes'];
        }
        return view('home.profile', ['info' => $info, 'follows' => $follows, 'favorites' => $favorites]);
    }
}
